package com.lcxw.hxzbadmin.controller.membercontroller;

import com.alibaba.fastjson.JSONObject;
import com.lcxw.hxzbadmin.entity.requestbean.GetAddCoinDetailReq;
import com.lcxw.hxzbadmin.entity.responseBean.ResponseData;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.lcxw.hxzbapi.entity.pojo.AddCoin;
import com.lcxw.hxzbapi.entity.response.Response;

@RestController
@CrossOrigin
@Slf4j
@RequestMapping("admin/user")
public class MemberCoinController {

    @Resource
    MemberCoinRealization memberCoinRealization;

    /**
     * 1、为用户加值接口
     *
     * @param requestParams
     * @return
     */
    @PostMapping("/coin/add")
    public Response userCoinAdd(HttpServletRequest request, @RequestBody JSONObject requestParams) {
        String adminName = requestParams.getString("adminName");
        long userId = Long.parseLong(requestParams.getString("userId"));
        int coin = requestParams.getInteger("coin");
        log.info("admin {} add {} coin for user {}", adminName, coin, userId);
        //先操作给用户添加虚拟币
        try {
            memberCoinRealization.addCoin(userId, coin);
        } catch (Exception e) {
            return Response.dbFail(log, "admin add coin for user");
        }
        String ip = request.getRemoteAddr();
        //然后将加值记录存到数据库中
        try {
            memberCoinRealization.addCoinDetail(userId, coin, adminName, ip);
        } catch (Exception e) {
            return Response.dbFail(log, "add coin detail to db");
        }
        return Response.ok();

    }

    /**
     * 2、用户加值记录查询接口
     */
    @PostMapping("/coin/addDetail")
    public Response addCoinDetail(@Valid @RequestBody GetAddCoinDetailReq requestParams) {
        Long userId = requestParams.getUserId();
        String startTime = requestParams.getStartTime();
        String endTime = requestParams.getEndTime();
        String admin = requestParams.getAdmin();
        int pageIndex = requestParams.getPageNum();
        int pageSize = requestParams.getPageSize();

        int sum = memberCoinRealization.getSumDetailsDync(userId, startTime, endTime, admin);
        List<AddCoin> addCoins = memberCoinRealization
            .getDetailDync(userId, startTime, endTime, admin, pageIndex, pageSize);
        ResponseData data = new ResponseData();
        data.setTotal(sum);
        data.setList(addCoins);
        return Response.ok(data);
    }


}
